﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Channels;

namespace JXT.PrimaryKey.Batman.Core.WcfService
{
    /// <summary>
    /// 服务Message扩展类
    /// </summary>
    public static class MessageExtensions
    {
        // Methods
        public static HttpResponseMessageProperty GetHttpResponseProperty(this Message message)
        {
            if (message.Properties.ContainsKey(HttpResponseMessageProperty.Name)) return (HttpResponseMessageProperty)message.Properties[HttpResponseMessageProperty.Name];
            return null;
        }

        public static NameValueCollection GetRequestUriTemplateMatchVariables(this Message message)
        {
            string name = "UriTemplateMatchResults";
            if (message.Properties.ContainsKey(name))
            {
                UriTemplateMatch match = message.Properties[name] as UriTemplateMatch;
                if (match != null) return match.BoundVariables;
            }
            return null;
        }

        public static void SetHttpResponseProperty(this Message message, HttpResponseMessageProperty httpResponse)
        {
            if (message.Properties.ContainsKey(HttpResponseMessageProperty.Name)) message.Properties.Remove(HttpResponseMessageProperty.Name);
            message.Properties.Add(HttpResponseMessageProperty.Name, httpResponse);
        }

        public static void SetWebContentFormatProperty(this Message message, WebContentFormat format)
        {
            if (message.Properties.ContainsKey("WebBodyFormatMessageProperty")) message.Properties.Remove("WebBodyFormatMessageProperty");
            message.Properties.Add("WebBodyFormatMessageProperty", new WebBodyFormatMessageProperty(format));
        }

        public static void UpdateHttpProperty(this Message message)
        {
            HttpResponseMessageProperty httpResponseProperty = message.GetHttpResponseProperty();
            if (httpResponseProperty == null)
            {
                httpResponseProperty = new HttpResponseMessageProperty();
                message.SetHttpResponseProperty(httpResponseProperty);
            }
            httpResponseProperty.StatusCode = WebOperationContext.Current.OutgoingResponse.StatusCode;
            httpResponseProperty.StatusDescription = WebOperationContext.Current.OutgoingResponse.StatusDescription;
            httpResponseProperty.SuppressEntityBody = WebOperationContext.Current.OutgoingResponse.SuppressEntityBody;
            for (int i = 0; i < WebOperationContext.Current.OutgoingResponse.Headers.Count; i++)
            {
                httpResponseProperty.Headers[WebOperationContext.Current.OutgoingResponse.Headers.Keys[i]] = WebOperationContext.Current.OutgoingResponse.Headers[i];
            }
        }
    }


}
